import {WL} from "@/proto/weilapb";
import {WeilaPbFriendWrapper} from "@/proto/weilapb_friend_wrapper";
import {Weila_MemDB} from "@/mem_store/weila_db";
import {convertFromUserRaw} from "@/proto/weilapb_utils";
import {WL_CoreInterface} from "@/core/weila_datas";


export default class WLFriendModule {
    constructor(private coreInterface: WL_CoreInterface) {
        this.coreInterface.registerPbMsgHandler(WL.Service.ServiceID.SERVICE_FRIEND, this.onPbMsgHandler.bind(this));
    }

    private onPbMsgHandler(data: any): void {
        const serverMessage = data as WL.Service.IServiceMessage;
        const serviceHead = serverMessage.serviceHead;
        if (serviceHead!.commandType == WL.Service.CommandType.COMMAND_RESPONSE) {
            switch (serviceHead!.commandId) {
                case WL.Friend.FriendCommandId.FRIEND_COMMAND_GET_FRIEND_USERINFO: {
                    this.coreInterface.rspPbMsg(serviceHead!.seq!, serviceHead!.resultCode!, serverMessage.friendMessage ? serverMessage.friendMessage.rspGetFriendUserInfo : null);
                }
                break;
            }
        }
    }

    public async getFriendUserInfos(userIds: number[]): Promise<boolean> {
        const buildResult = WeilaPbFriendWrapper.buildGetFriendUserInfoReq(userIds);
        if (buildResult.resultCode == 0) {
            try {
                const rspGetFriendUser = await this.coreInterface.sendPbMsg(buildResult) as WL.Friend.IRspGetFriendUserInfo;
                const userInfoRaws = rspGetFriendUser.userInfos!.map((value: WL.Common.IUserInfo) => {
                    return convertFromUserRaw(value);
                })
                Weila_MemDB.getInstance().putUsers(userInfoRaws);
            }catch (e) {
                return Promise.reject('获取好友信息失败:' + e);
            }
        }

        return Promise.reject('创建信息出错:' + buildResult.resultCode);
    }

}
